#!/usr/bin/python
#coding:utf-8
'''
mysql连接操作:pip install pymysql
博客：https://www.cnblogs.com/yuhou/p/10893056.html

表信息：
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for test
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test`  (
  `id` int NOT NULL,
  `num` int NULL DEFAULT NULL,
  `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '功能表' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

''' 
import pymysql

# 连接数据库
connect = pymysql.Connect(
    host='localhost',
    port=3306,
    user='root',
    passwd='wang',
    db='test',
    charset='utf8'
)

# 获取游标
cursor = connect.cursor()

# 插入数据
sql = "INSERT INTO test (id, num, name) VALUES ( %d, %d, '%s' )"
data = (4, 4, 'python测试')
cursor.execute(sql % data)
connect.commit()
print('成功插入', cursor.rowcount, '条数据')

# 修改数据
sql = "UPDATE test SET num = %d WHERE id = %d"
data = (5, 4)
cursor.execute(sql % data)
connect.commit()
print('成功修改', cursor.rowcount, '条数据')

# 查询数据
sql = "SELECT id,num,name FROM test"
cursor.execute(sql)
for row in cursor.fetchall():
    print("Id:%d Num:%d Name:%s" % row)
print('共查找出', cursor.rowcount, '条数据')

# 删除数据
sql = "DELETE FROM test WHERE id=%d"
data = (4)
cursor.execute(sql % data)
connect.commit()
print('成功删除', cursor.rowcount, '条数据')

# 事务处理
# sql_1 = "UPDATE test SET saving = saving + 1000 WHERE account = '18012345678' "
# sql_2 = "UPDATE test SET expend = expend + 1000 WHERE account = '18012345678' "
# sql_3 = "UPDATE test SET income = income + 2000 WHERE account = '18012345678' "

# try:
#     cursor.execute(sql_1)  # 储蓄增加1000
#     cursor.execute(sql_2)  # 支出增加1000
#     cursor.execute(sql_3)  # 收入增加2000
# except Exception as e:
#     connect.rollback()  # 事务回滚
#     print('事务处理失败', e)
# else:
#     connect.commit()  # 事务提交
#     print('事务处理成功', cursor.rowcount)

# 关闭连接
cursor.close()
connect.close()


# ---------------mysql批量添加----------------------------------
import pymysql
 
# 数据库连接配置
config = {
    'host': 'localhost',
    'user': 'your_username',
    'password': 'your_password',
    'database': 'your_database',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}
 
# 要批量插入的数据 数组中元素为元组
data_to_insert = [
    (1, 'Name1', 'Address1'),
    (2, 'Name2', 'Address2'),
    (3, 'Name3', 'Address3'),
    # ...
]
 
# 建立数据库连接
connection = pymysql.connect(**config)
 
try:
    # 创建游标对象
    with connection.cursor() as cursor:
        # SQL 语句，其中 %s 占位符用于后续数据的插入
        sql = "INSERT INTO your_table (id, name, address) VALUES (%s, %s, %s)"
        
        # 执行批量插入
        cursor.executemany(sql, data_to_insert)
        
        # 提交事务
        connection.commit()
 
finally:
    # 关闭数据库连接
    connection.close()
